<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue';

import Stepper from 'primevue/stepper';
import StepperPanel from 'primevue/stepperpanel';
import FileUpload from 'primevue/fileupload';
import Splitter from 'primevue/splitter';
import SplitterPanel from 'primevue/splitterpanel';
import Slider from 'primevue/slider';
import SelectButton from 'primevue/selectbutton';
import Editor from 'primevue/editor';

import { useToast } from "primevue/usetoast";
// @ts-ignore
import { draw } from "@/lib/draw"; // 矩形绘制方法

import { UploadImageApi } from "@/api/upload";

// onMounted(() => {
//   initCanvas(); // 确保在组件挂载后初始化画布
// });


// 进度条
const progressValue = ref(0); // 进度条的值
const uploadProgress = ref(0); // 实际上传的进度



const toast = useToast();
const img1 = ref();
const img2 = ref();

// 矩形选项框数组
let markList: { x: number; y: number; w: number; h: number }[] = [];
const markCanvas = ref();
const markCanvas2 = ref();
const downloadUrl = ref('');

// 图片识别结果
const ocrValue = ref('请先上传试卷');


// 保存图片src 临时存储
const base64url = ref<any>("");

const Base64Uploader = (event: any) => {

    img1.value = "sss";
    const file = event.files[0];
    const reader = new FileReader();
    // 直接读取文件
    reader.readAsDataURL(file);
    
    reader.onload = () => {
        
        
        img1.value.src = reader.result as string;
        base64url.value = reader.result as string;
        img2.value = reader.result as string;


    };
};

// 清除图片
const onClearBase64Url = () => {
    img1.value = "";
};



// 步骤条切换
const handleStepChange = (event: any) => {
    if (event.index == 1) {
        // 确保canvas dom挂载完成后执行初始化
        nextTick(() => {
            img2.value.src = base64url.value;
            initCanvas();
        });
    } else if (event.index == 2) {
        if (downloadUrl.value) {
            // // 将Base64字符串转换为文件
            // const file = base64ToFile(markCanvas2.value.toDataURL('image/jpeg'), 'image.jpg');
            const base64Image = markCanvas2.value.toDataURL('image/jpeg')

            // 提取Base64编码中的图片数据部分
            const matches = base64Image.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
            const response = matches && matches.length > 2 ? matches[2] : null;

            // 创建一个Blob对象
            const blob = new Blob([atob(response)], { type: 'image/jpeg' });

            // 创建一个指向该Blob的URL
            // const objectURL = URL.createObjectURL(blob);

            // 创建一个File对象
            const file = new File([blob], 'temp.jpg', {
                type: 'image/jpeg',
                lastModified: new Date().getTime() // 使用时间戳
            });

            // 创建FormData对象并添加文件
            const formData = new FormData();
            formData.append('file', file);

            // 上传图片
            UploadImageApi(formData).then(res => {
                progressValue.value = 30;
                if (res.code == 200) {
                console.log(res.data);
                
                    progressValue.value = 100;
                    toast.add({ severity: 'success', summary: '上传成功', detail: '图片上传成功', life: 3000 });
                    // console.log(res.data);
                }
            }).catch(err => {
                toast.add({ severity: 'error', summary: '上传失败', detail: '图片上传错误', life: 3000 });
            });
        } else {
            toast.add({ severity: 'error', summary: '请先裁剪图片', detail: '未检测到有效图片', life: 3000 });
        }

    } else {
        // 所有条件都为假时执行
    }
}



// 初始化矩形绘制
const initCanvas = () => {
    const cav = markCanvas.value;
    const ctx = cav.getContext('2d');
    ctx.strokeStyle = 'blue';
    cav.style.cursor = 'crosshair';

    markList.forEach((value, index, array) => {
        let newValue = {
            x: value.x,
            y: value.y,
            w: value.w,
            h: value.h,
        };
        markList.splice(index, 1, newValue);
    });
    if (markList.length !== 0) {
        markList.forEach((value) => {
            ctx.rect(value.x, value.y, value.w, value.h);
            ctx.stroke();
        });
    }
    draw(cav, markList);
};

const getCroppedImageData = () => {

    let ctx1 = markCanvas2.value.getContext('2d');
    let height = (markList[0].h / img2.value.height) * img2.value.naturalHeight;
    let width = (markList[0].w / img2.value.width) * img2.value.naturalWidth;

    // 清除当前裁剪画布
    ctx1.clearRect(0, 0, markCanvas2.value.width, markCanvas2.value.height);
    ctx1.drawImage(img2.value, markList[0].x / img2.value.width * img2.value.naturalWidth, markList[0].y / img2.value.height * img2.value.naturalHeight, width, height, 0, 0, markList[0].w * 2, markList[0].h * 2);
    const croppedImageData = markCanvas2.value.toDataURL('image/jpeg');
    downloadUrl.value = croppedImageData;
};

// 下载裁剪后的图片
const downloadCroppedImage = () => {

    if (downloadUrl.value === '') {
        // alert("请先点击裁剪按钮");
        toast.add({ severity: 'error', summary: '请先点击裁剪按', detail: '裁剪完成后才可以下载', life: 3000 });

    } else {
        const a = document.createElement('a');
        a.href = downloadUrl.value;
        a.download = 'cropped.jpg';
        a.click();
    }
}


// 删除最后一个矩形的方法
const deleteLastRectangle = () => {
    if (markList.length > 0) {
        // 清除当前裁剪画布
        let ctx1 = markCanvas.value.getContext('2d');
        markList = []
        ctx1.clearRect(0, 0, markCanvas.value.width, markCanvas.value.height);
        initCanvas();
    }
};

const filter = ref(0);
const filterOptions = ref([
    { label: '3倍', value: 30 },
    { label: '4倍', value: 40 },
    { label: '5倍', value: 50 }
]);




const filterStyle = computed(() => {
    return {
        // filter: `contrast(${this.filterValues[0]}%) brightness(${this.filterValues[1]}%) sepia(${this.filterValues[2]}%)`
    };
})


const onValueChange = () => {
    onSlideChange()
}

const onSlideChange = () => {
    const multiple = filter.value / 10
    let ctx1 = markCanvas2.value.getContext('2d');
    let height = (markList[0].h / img2.value.height) * img2.value.naturalHeight;
    let width = (markList[0].w / img2.value.width) * img2.value.naturalWidth;

    // 清除当前裁剪画布
    ctx1.clearRect(0, 0, markCanvas2.value.width, markCanvas2.value.height);
    ctx1.drawImage(img2.value, markList[0].x / img2.value.width * img2.value.naturalWidth, markList[0].y / img2.value.height * img2.value.naturalHeight, width, height, 0, 0, markList[0].w * multiple, markList[0].h * multiple);
    const croppedImageData = markCanvas2.value.toDataURL('image/jpeg');
    downloadUrl.value = croppedImageData;
}


</script>

<template>
    <div class="card flex p-1">
        <Stepper linear :activeStep="0" @step-change="handleStepChange">
            <StepperPanel header="上传试卷">
                <template #header="{ index, clickCallback }">
                    <button class="bg-transparent border-none inline-flex flex-column gap-2" @click="clickCallback">
                        <svg t="1708955578988" class="icon" viewBox="0 0 1024 1024" version="1.1"
                            xmlns="http://www.w3.org/2000/svg" p-id="6175" width="50" height="50">
                            <path
                                d="M847.644444 1024H150.755556c-48.355556-5.688889-88.177778-45.511111-93.866667-93.866667V93.866667C62.577778 45.511111 102.4 8.533333 150.755556 0h466.488888l327.111112 278.755556v651.377777c-8.533333 48.355556-48.355556 88.177778-96.711112 93.866667z m0-696.888889h-184.888888c-25.6-2.844444-42.666667-22.755556-45.511112-45.511111V93.866667H196.266667c-25.6 0-45.511111 19.911111-45.511111 45.511111v745.244444c5.688889 22.755556 22.755556 42.666667 45.511111 45.511111h605.866666c25.6-2.844444 45.511111-22.755556 45.511111-45.511111V327.111111z m-546.133333 512c-5.688889 0-8.533333-5.688889-8.533333-8.533333 0-2.844444 2.844444-8.533333 5.688889-8.533334C429.511111 768 571.733333 739.555556 711.111111 733.866667v2.844444c11.377778 0 25.6-2.844444 36.977778-2.844444v5.688889c-142.222222 14.222222-281.6 42.666667-415.288889 85.333333-8.533333 8.533333-19.911111 11.377778-31.288889 14.222222zM625.777778 676.977778c-14.222222 0-28.444444-2.844444-36.977778-14.222222s-17.066667-22.755556-17.066667-36.977778c0-39.822222 11.377778-76.8 36.977778-108.088889 22.755556-31.288889 56.888889-54.044444 93.866667-68.266667 14.222222 0 25.6 8.533333 31.288889 19.911111-2.844444 2.844444-5.688889 5.688889-8.533334 5.688889 14.222222 5.688889 19.911111 17.066667 19.911111 31.288889 2.844444 79.644444-48.355556 150.755556-119.466666 170.666667z m76.8-182.044445c-5.688889 2.844444-14.222222 8.533333-19.911111 14.222223-2.844444 0-2.844444-2.844444-2.844445-5.688889-42.666667 25.6-71.111111 71.111111-73.955555 119.466666 0 5.688889 2.844444 25.6 11.377777 22.755556 14.222222-5.688889 25.6-11.377778 34.133334-22.755556l28.444444-31.288889c17.066667-22.755556 28.444444-51.2 34.133334-79.644444 5.688889-8.533333-2.844444-14.222222-11.377778-17.066667z m-162.133334-199.111111H201.955556c-11.377778 0-19.911111-8.533333-19.911112-19.911111 0-5.688889 2.844444-11.377778 5.688889-14.222222 2.844444-5.688889 8.533333-8.533333 14.222223-8.533333H540.444444c5.688889 0 11.377778 2.844444 14.222223 5.688888 2.844444 2.844444 5.688889 8.533333 5.688889 14.222223s-2.844444 11.377778-5.688889 14.222222-8.533333 8.533333-14.222223 8.533333zM201.955556 338.488889H369.777778c5.688889 0 11.377778 2.844444 14.222222 5.688889s5.688889 8.533333 5.688889 14.222222-2.844444 11.377778-5.688889 14.222222-8.533333 5.688889-14.222222 5.688889H201.955556c-11.377778 0-19.911111-8.533333-19.911112-19.911111 0-5.688889 2.844444-11.377778 5.688889-14.222222 2.844444-2.844444 8.533333-5.688889 14.222223-5.688889z m108.088888 196.266667l-31.288888 14.222222c-2.844444 2.844444-5.688889 2.844444-8.533334 2.844444-2.844444 0-2.844444-5.688889-2.844444-8.533333 0-8.533333 5.688889-14.222222 14.222222-17.066667 17.066667-14.222222 34.133333-25.6 54.044444-34.133333 8.533333 2.844444 14.222222 11.377778 17.066667 19.911111 0 8.533333 0 8.533333-39.822222 99.555556-14.222222 28.444444-25.6 59.733333-28.444445 91.022222 0 2.844444 2.844444 8.533333 2.844445 11.377778v2.844444l-2.844445 2.844444c-2.844444 0-5.688889 0-5.688888-2.844444-14.222222 0-25.6-8.533333-28.444445-22.755556 0-22.755556 5.688889-48.355556 14.222222-68.266666 11.377778-31.288889 28.444444-59.733333 45.511111-91.022222z m250.311112-2.844445c5.688889 76.8-42.666667 145.066667-116.622223 164.977778-14.222222 0-28.444444-2.844444-36.977777-14.222222-11.377778-8.533333-17.066667-22.755556-17.066667-36.977778 0-39.822222 11.377778-76.8 36.977778-108.088889 22.755556-31.288889 56.888889-54.044444 93.866666-68.266667 14.222222 0 25.6 8.533333 31.288889 19.911111-2.844444 2.844444-5.688889 5.688889-8.533333 5.688889 8.533333 8.533333 17.066667 22.755556 17.066667 36.977778z m-39.822223-17.066667c-5.688889 2.844444-14.222222 8.533333-19.911111 14.222223-2.844444 0-2.844444-2.844444-2.844444-5.688889-42.666667 25.6-71.111111 71.111111-73.955556 119.466666 0 5.688889 2.844444 25.6 11.377778 22.755556 14.222222-5.688889 25.6-11.377778 34.133333-22.755556l28.444445-31.288888c17.066667-22.755556 28.444444-51.2 34.133333-79.644445 5.688889-8.533333-2.844444-14.222222-11.377778-17.066667z m-258.844444 273.066667c130.844444-54.044444 273.066667-82.488889 412.444444-88.177778v2.844445c14.222222 0 25.6-2.844444 36.977778-2.844445v5.688889c-142.222222 14.222222-281.6 42.666667-415.288889 85.333334-11.377778 5.688889-19.911111 8.533333-31.288889 11.377777h-2.844444c-2.844444 0-5.688889-2.844444-5.688889-8.533333l5.688889-5.688889z"
                                fill="#666666" p-id="6176"></path>
                        </svg>
                    </button>
                    <span>上传试卷&nbsp;</span>
                </template>
                <template #content="{ nextCallback }">
                    <div class="flex  h-10 w-80 gap-2 mb-3">
                        <FileUpload class="p-2" mode="basic" name="demo[]" :auto=true accept="image/*" customUpload
                            @uploader="Base64Uploader" chooseLabel="上传图片" />

                        <Button label="清除" icon="pi pi-times" severity="danger" @click="onClearBase64Url" />
                    </div>
                    <div>
                        <img v-if="img1" ref="img1" alt="image" style="width:400px; height: 300px;" />

                        <div v-else class="flex items-center justify-center flex-col">
                            <i class="pi pi-cloud-upload border-2  p-5 text-8xl" />
                            <p class="mt-4 mb-0">请上传图片</p>
                        </div>

                    </div>
                    <div class="flex pt-4 justify-end">
                        <Button label="下一步" icon="pi pi-arrow-right" iconPos="right" @click="nextCallback" />
                    </div>
                </template>
            </StepperPanel>
            <StepperPanel>
                <template #header="{ index, clickCallback }">
                    <button class="bg-transparent border-none inline-flex flex-column gap-2" @click="clickCallback">
                        <svg t="1708956790865" class="icon" viewBox="0 0 1024 1024" version="1.1"
                            xmlns="http://www.w3.org/2000/svg" p-id="7881" width="50" height="50">
                            <path
                                d="M832 728V250.5c0-8.5 3.4-16.6 9.4-22.6L1001 68.3c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L796.1 182.6c-6 6-14.1 9.4-22.6 9.4H296c-4.4 0-8-3.6-8-8V8c0-4.4-3.6-8-8-8h-80c-4.4 0-8 3.6-8 8v176c0 4.4-3.6 8-8 8H8c-4.4 0-8 3.6-8 8v80c0 4.4 3.6 8 8 8h176c4.4 0 8 3.6 8 8v472c0 35.3 28.7 64 64 64h472c4.4 0 8 3.6 8 8v176c0 4.4 3.6 8 8 8h80c4.4 0 8-3.6 8-8V840c0-4.4 3.6-8 8-8h176c4.4 0 8-3.6 8-8v-80c0-4.4-3.6-8-8-8H840c-4.4 0-8-3.6-8-8zM296 288h375.4c7.1 0 10.7 8.6 5.7 13.7L301.7 677.1c-5 5-13.7 1.5-13.7-5.7V296c0-4.4 3.6-8 8-8z m432 448H352.6c-7.1 0-10.7-8.6-5.7-13.7l375.4-375.4c5-5 13.7-1.5 13.7 5.7V728c0 4.4-3.6 8-8 8z"
                                p-id="7882" fill="#666666"></path>
                        </svg>
                    </button>
                    <span>区域选择&nbsp;</span>
                </template>
                <template #content="{ prevCallback, nextCallback }">
                    <div>
                        <Splitter style="height: 450px">
                            <SplitterPanel class="flex align-items-center justify-content-center" :size="60"
                                :minSize="10">
                                <div style="position: relative; width: auto; height: 450px;">
                                    <img :src="base64url" ref="img2" alt=""
                                        style="width: auto; max-width: 1000px;height: 100%;" />
                                    <canvas ref="markCanvas" tabindex="0" width="1000" height="450"
                                        style="position: absolute;z-index: 999;top: 0;left: 0;"></canvas>
                                </div>
                            </SplitterPanel>
                            <SplitterPanel class="flex align-items-center justify-content-center" :size="40"
                                style="position: relative;">
                                <canvas ref="markCanvas2" tabindex="0" width="1000" height="450"
                                    style="position: absolute;;top: 0;"></canvas>
                            </SplitterPanel>
                        </Splitter>
                    </div>
                    <div class="flex pt-4 justify-between">
                        <Button label="返回" severity="secondary" icon="pi pi-arrow-left" @click="prevCallback" />
                        <p>注意：中间可拖动用于查看裁剪前后对比</p>
                        <Button label="下一步" icon="pi pi-arrow-right" iconPos="right" @click="nextCallback" />
                    </div>
                </template>
            </StepperPanel>
            <StepperPanel header="Header III">
                <template #header="{ index, clickCallback }">
                    <button class="bg-transparent border-none inline-flex flex-column gap-2" @click="clickCallback">
                        <svg t="1708957815693" class="icon" viewBox="0 0 1024 1024" version="1.1"
                            xmlns="http://www.w3.org/2000/svg" p-id="12880" width="50" height="50">
                            <path
                                d="M640.189 960.294l-0.131-64 254.651-0.522 1.285-255.968 64 0.322-1.605 319.515-318.2 0.653z m-256.239-0.075l-318.197-1.237 0.251-319.042 64 0.051-0.201 255.239 254.396 0.989-0.249 64zM66.004 383.837L65.53 64.399l318.728 1.829-0.367 63.999-254.265-1.459 0.378 254.975-64 0.094zM897.495 383l-0.661-252.989-254.683 0.217-0.055-64 318.569-0.271 0.829 316.876-63.999 0.167zM404.866 510.522c0 24.75-5.328 46.895-15.984 66.43-10.656 19.537-25.553 34.719-44.688 45.547-19.137 10.828-40.562 16.242-64.281 16.242-23.146 0-44.201-5.242-63.164-15.727-18.965-10.484-33.717-25.207-44.258-44.172-10.543-18.963-15.812-40.418-15.812-64.367 0-25.093 5.328-47.665 15.984-67.718 10.656-20.05 25.609-35.549 44.859-46.492 19.25-10.941 41.135-16.414 65.656-16.414 23.604 0 44.714 5.242 63.336 15.727 18.619 10.484 33 25.438 43.141 44.859s15.211 41.451 15.211 66.085z m-78.719 2.062c0-20.281-3.896-36.265-11.688-47.953-7.793-11.688-18.45-17.531-31.969-17.531-14.781 0-26.297 5.615-34.547 16.844-8.25 11.231-12.375 27.1-12.375 47.609 0 20.053 4.096 35.693 12.289 46.922 8.191 11.23 19.336 16.844 33.43 16.844 8.594 0 16.328-2.52 23.203-7.562 6.875-5.041 12.203-12.26 15.984-21.656 3.782-9.396 5.673-20.566 5.673-33.517zM623.147 627.741c-20.396 7.332-43.943 11-70.641 11-26.24 0-48.872-5.012-67.891-15.039-19.021-10.025-33.545-24.291-43.57-42.797-10.028-18.504-15.039-39.846-15.039-64.023 0-26.009 5.613-49.156 16.844-69.437 11.229-20.281 27.097-35.949 47.609-47.008 20.51-11.057 44.114-16.586 70.813-16.586 21.312 0 41.938 2.578 61.875 7.734v68.578c-6.875-4.125-15.068-7.332-24.578-9.625a122.892 122.892 0 0 0-28.875-3.438c-20.168 0-36.066 5.787-47.695 17.359-11.631 11.575-17.446 27.271-17.446 47.093 0 19.709 5.814 35.264 17.446 46.664 11.629 11.402 27.184 17.102 46.664 17.102 17.988 0 36.15-4.582 54.484-13.75v66.173zM789.351 634.444l-18.391-53.109c-3.553-10.426-8.164-18.619-13.836-24.578-5.672-5.957-11.832-8.938-18.477-8.938h-2.922v86.625h-74.25V387.975h98.656c34.488 0 59.955 5.645 76.398 16.93 16.441 11.287 24.664 28.217 24.664 50.789 0 16.959-4.785 31.168-14.352 42.625-9.568 11.458-23.805 19.765-42.711 24.921v0.688c10.426 3.209 19.105 8.422 26.039 15.641 6.932 7.219 13.148 17.934 18.648 32.141l24.234 62.734h-83.7z m-7.047-168.265c0-8.25-2.521-14.781-7.562-19.594-5.043-4.812-12.949-7.219-23.719-7.219h-15.297v56.375h13.406c9.969 0 17.988-2.807 24.062-8.422 6.073-5.613 9.11-12.659 9.11-21.14z"
                                p-id="12881" fill="#666666"></path>
                        </svg>
                    </button>
                    <span>试卷识别&nbsp;</span>
                </template>
                <template #content="{ prevCallback }">
                    <progressBar :value="progressValue"></progressBar>
                    <br />
                    <Editor v-model="ocrValue" editorStyle="height: 320px" />
                    <div class="flex pt-4 justify-content-start">
                        <Button label="返回" severity="secondary" icon="pi pi-arrow-left" @click="prevCallback" />
                    </div>
                </template>
            </StepperPanel>
        </Stepper>

        <div class="flex justify-center item-center flex-col gap-2" v-show="markCanvas2">
            <div class="flex flex-col items-center  mb-10">
                <p>放大倍数</p>
                <SelectButton v-model="filter" :options="filterOptions" optionLabel="label" optionValue="value"
                    class="mb-5" @change="onValueChange" />
                <Slider v-model="filter" class=" w-40" :min="0" :max="50" @change="onSlideChange" />
            </div>
            <Button label="裁剪区域" icon="pi pi-clone" @click="getCroppedImageData" />
            <Button label="清除选框" icon="pi pi-eraser" severity="danger" @click="deleteLastRectangle" />
            <Button label="下载选框" icon="pi pi-download" severity="info" @click="downloadCroppedImage" />
        </div>
    </div>
</template>
<style lang="scss">
.p-stepper {
    flex-basis: 50rem;
}


/* 默认状态下的分割线样式 */
.p-splitter-gutter {
    background-color: #e0e0e0;
    /* 分割线的颜色 */
    border: none;
    /* 移除默认边框 */
    width: 4px;
    /* 分割线的宽度 */
}

/* 分割线手柄的样式 */
.p-splitter-gutter-handle {
    background-color: #757575;
    /* 手柄的颜色 */
    width: 4px;
    /* 手柄的宽度，与分割线宽度保持一致 */
}

/* 当分割线处于活动状态时的样式 */
.p-splitter-gutter[data-p-gutter-resizing="true"] {
    background-color: #a0e1cb;
    /* 活动状态下分割线的颜色 */
}

/* 当分割线处于活动状态时的手柄样式 */
.p-splitter-gutter-handle[data-pc-section="gutterhandler"] {
    background-color: #10B981;
    /* 活动状态下手柄的颜色 */
}

.p-highlight {
    color: #10B981;

    svg path {
        fill: #10B981;
    }
}
</style>